package com.gnomon.epsos.servlet;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.*;
import javax.servlet.*;
import org.apache.log4j.Logger;
import org.opensaml.saml2.core.Assertion;

import com.gnomon.epsos.model.Patient;
import com.gnomon.epsos.model.ViewResult;
import com.gnomon.epsos.service.EpsosHelperService;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.User;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.portlet.PortletProps;

import epsos.openncp.protocolterminator.ClientConnectorConsumer;
import epsos.openncp.protocolterminator.clientconnector.EpsosDocument1;
import epsos.openncp.protocolterminator.clientconnector.GenericDocumentCode;

public class DispenseServlet extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static Logger log = Logger.getLogger("dispenseServlet");
	
	public void doPost (HttpServletRequest req,
		    HttpServletResponse res)
		throws ServletException, IOException
  {
		log.info("dispensing ...");

		HttpSession session = req.getSession();
		String selectedCountry = (String) session.getAttribute("selectedCountry");
		Patient patient = (Patient) session.getAttribute("patient");
		Assertion hcpAssertion = (Assertion) session.getAttribute("hcpAssertion");
		Assertion trcAssertion = (Assertion) session.getAttribute("trcAssertion");
		User user = (User) session.getAttribute("user");

		byte[] edBytes = null;
		try {
			byte[] epBytes = (byte[]) session.getAttribute("epBytes");
			List<ViewResult> lines=EpsosHelperService.parsePrescriptionDocumentForPrescriptionLines(epBytes);

			String[] dispensedIds = new String[lines.size()];
			for (int i=0;i<lines.size();i++)
			{
				dispensedIds[i]=req.getParameter("dispensationid_" + i);
			}
			
			String language = ParamUtil.getString(req, "language");;
			String fullname = "EPSOS PORTAL";
			try {
				fullname = PortalUtil.getUser(req).getFullName();
			} catch (Exception e1) {
			
			} 
			
			
			if (dispensedIds != null)
			{
				List<String> dispensedIdsList = Arrays.asList(dispensedIds);
				ArrayList<ViewResult> dispensedLines = new ArrayList<ViewResult>();
				for (ViewResult line: lines)
				{
					int id = line.getMainid();
					String measures_id = req.getParameter("measures_"+id); 
					String dispensed_id = req.getParameter("dispensationid_"+id); //field1
					String dispensedProduct = req.getParameter("dispensedProductValue_"+id);
					if (Validator.isNull(dispensedProduct)) dispensedProduct=line.getField1()+"";
					String dispensed_substitute = req.getParameter("dispense_"+id); // field3
					boolean substitute = GetterUtil.getBoolean(dispensed_substitute, false);
					String dispensed_quantity = req.getParameter("dispensedPackageSize_"+id); // field7 //lathos
					if (Validator.isNull(dispensed_quantity)) dispensed_quantity=line.getField21()+"";
					String dispensed_name = dispensedProduct;
					String dispensed_strength = line.getField3()+"";
					String dispensed_form =  line.getField4()+"";
					String dispensed_package =  line.getField4()+""; //request.getParameter("packaging2_"+id); // field6
					String dispensed_nrOfPacks =  line.getField8().toString();
					String prescriptionid = line.getField14()+""; // field9 //lathos
					String materialid = line.getField19()+""; // field10
					String activeIngredient = line.getField2().toString();
					
					ViewResult d_line = new ViewResult(
							id, 
							dispensed_id, 
							dispensed_name, 
							substitute,
							dispensed_strength, 
							dispensed_form, 
							dispensed_package, 
							dispensed_quantity, 
							dispensed_nrOfPacks, 
							prescriptionid, 
							materialid, 
							activeIngredient,
							measures_id);

					dispensedLines.add(d_line);
				}

				if (dispensedLines.size() > 0)
					{
					edBytes = EpsosHelperService.generateDispensationDocumentFromPrescription2(epBytes, 
							lines, 
							dispensedLines, 
							user);
					}
				
				
				if (Validator.isNotNull(edBytes))
					{
					String serviceUrl = PortletProps.get("client.connector.service.url");
					ClientConnectorConsumer proxy = new ClientConnectorConsumer(serviceUrl);

					//
					GenericDocumentCode classCode = GenericDocumentCode.Factory
							.newInstance();
					classCode.setNodeRepresentation(PortletProps
							.get("dispensation.classCode"));
					classCode.setSchema(PortletProps.get("classcode.schema"));
					classCode.setValue(PortletProps.get("dispensation.value"));

					GenericDocumentCode formatCode = GenericDocumentCode.Factory
							.newInstance();

					formatCode.setSchema(PortletProps
							.get("dispensation.formatcode.codingschema"));
					formatCode.setNodeRepresentation(PortletProps
							.get("dispensation.formatcode.noderepresentation"));
					formatCode.setValue(PortletProps
							.get("dispensation.formatcode.displayname"));

					EpsosDocument1 document = EpsosDocument1.Factory.newInstance();
					document.setAuthor(user.getFullName());
					Calendar cal = Calendar.getInstance();
					document.setCreationDate(cal);
					document.setDescription("eDispensation");
					document.setTitle("eDispensation");
					document.setUuid(UUID.randomUUID() + "");
					document.setClassCode(classCode);
					document.setFormatCode(formatCode);
					document.setBase64Binary(edBytes);
					
					proxy.submitDocument(hcpAssertion, trcAssertion, selectedCountry, document, patient.getPatientDemographics());
					}
					else
					{
					log.error("UPLOAD DISP DOC RESPONSE ERROR",null);
					req.setAttribute("exception", "UPLOAD DISP DOC RESPONSE ERROR");
					return;
					}
				}
		

		} catch (Exception ex) {
			res.setContentType("text/html");  
			   
			res.setHeader("Cache-Control", "no-cache");  
			res.setDateHeader("Expires", 0);  
			res.setHeader("Pragma", "No-cache");   

			OutputStream OutStream = res.getOutputStream();  
			OutStream.write(ex.getMessage().getBytes());  
			OutStream.flush();  
			OutStream.close(); 
			ex.printStackTrace();
		}

  
  
  }
}